﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Filters;
using STF.Blog.WebApp.Areas.ForumManage.Models.Admins;
using STF.Blog.WebApp.Areas.ForumManage.Models.Roles;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    [Login]
    public class AdminsController : Controller
    {

        private IAdminsService _ias;
        private IRolesService _irs;
        private IWebHostEnvironment _iwe;

        public AdminsController(IAdminsService ias, IRolesService irs, IWebHostEnvironment iwe)
        {
            _ias = ias;
            _irs = irs;
            _iwe = iwe;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search,int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _ias.GetByNameAsync(search);
            var dataList = new List<AdminsListViewModel>();

            foreach (var item in data)
            {
                var model = new AdminsListViewModel
                {
                    Id = item.Id,
                    NickName = item.NickName,
                    Birthday = item.Birthday.ToString("yyyy年MM月dd日"),
                    Gender = item.Gender,
                    Photo = item.Photo,
                    Tel = item.Tel,
                    Email = item.Email,
                    QQNumber = item.QQNumber,
                    Address = item.Address,
                    RolesTitle = await GetRolesTitle(item.RolesId),
                    UpdateTime = item.UpdateTime
                };
                dataList.Add(model);
            }

            ViewBag.Search = search;
            var pages = dataList.ToPagedList(page,PageConfig.PageSize);
            return View(pages);
        }

        /// <summary>
        /// 使用RolesId查询到对应权限名称的方法
        /// </summary>
        /// <param name="id">RolesId</param>
        /// <returns></returns>
        private async Task<string> GetRolesTitle(int id) 
        {
            var data = await _irs.GetByIdAsync(id);
            return data == null ? "" : data.Title;
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _ias.PutTrashAsync(id);
            return Redirect("~/ForumManage/Admins/Index");
        }

        [HttpGet]
        public async Task<IActionResult> Add() 
        {
            #region
            //var data = await _irs.GetAllUsersAsync();
            //var dataList = data.Select(a => new RolesListViewModel 
            //{
            //    Id = a.Id,
            //    Title = a.Title
            //});

            //ViewBag.RolesList = new SelectList(dataList,"Id","Title");
            #endregion

            await BindRolesList(null);

            return View(new AdminAddViewModel());
        }

        [HttpPost]
        public async Task<IActionResult> Add(AdminAddViewModel model) 
        {
            #region
            //string imageName;
            //if (ModelState.IsValid)
            //{
            //    imageName = DateTime.Now.ToString("yyyyMMddHHmmss") +
            //        model.Photo.FileName.Substring(model.Photo.FileName.LastIndexOf("."));

            //    string imagePath = _iwe.WebRootPath + @"\ImageHead\Admins\";
            //    string path = Path.Combine(imagePath, imageName);
            //    model.Photo.CopyTo(new FileStream(path, FileMode.Create));
            //}
            //else 
            //{
            //    imageName = "123.jpg";
            //}
            #endregion


            if (ModelState.IsValid) 
            {
                var imageName = await UploadFiles(model.Photo, @"\ImageHead\Admins");
                if (string.IsNullOrEmpty(imageName)) 
                {
                    imageName = "123.jpg";
                }

                var res = await _ias.AddUsersAsync(model.Account, model.Pwd, model.NickName, DateTime.Parse(model.Birthday)
                                         , model.Gender, imageName, model.Tel, model.Email, model.QQNumber, model.Address
                                         , model.RolesId);

                if (res > 0)
                {
                    return Redirect("~/ForumManage/Admins/Index");
                }
            }

            await BindRolesList(model.RolesId);

            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _ias.GetByIdAsync(id);

            await BindRolesList(data.RolesId);
            return View(new AdminsUpdateViewModel 
            {
                Id = data.Id,
                NickName = data.NickName,
                Birthday = data.Birthday,
                Gender = (int)data.Gender,
                Tel = data.Tel,
                Email = data.Email,
                QQNumber = data.QQNumber,
                Address = data.Address,
                Photo = data.Photo,
                Pwd = data.Pwd,
                RolesId = data.RolesId
            });

        }

        [HttpPost]
        public async Task<IActionResult> Update(AdminsUpdateViewModel model,IFormFile? image) 
        {
            if (ModelState.IsValid) 
            {
                var name = await UploadFiles(image, @"\ImageHead\Admins");
                var imgName = string.IsNullOrEmpty(name) ? model.Photo : name;
                var res = await _ias.UpdateUsersAsync(model.Id,model.Pwd,model.NickName
                                                     ,model.Birthday,(Gender)model.Gender, imgName, model.Tel
                                                     ,model.Email,model.QQNumber,model.Address,model.RolesId);

                if (res > 0)
                    return Redirect("~/ForumManage/Admins/Index");
            }

            await BindRolesList(model.RolesId);
            return View(model);
        }


        private async Task BindRolesList(int? rolesId) 
        {
            var data = await _irs.GetAllUsersAsync();
            var dataList = data.Select(a => new RolesListViewModel
            {
                Id = a.Id,
                Title = a.Title
            });

            if (rolesId == null)
                ViewBag.RolesList = new SelectList(dataList,"Id","Title");
            else
                ViewBag.RolesList = new SelectList(dataList, "Id", "Title",rolesId);

        }

        private async Task<string> UploadFiles(IFormFile image,string url) 
        {
            string imageName = "";
            if (image != null && image.FileName != null)
            {
                imageName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                    image.FileName.Substring(image.FileName.LastIndexOf("."));

                string imagePath = _iwe.WebRootPath + url;  // 上传到目标目录(文件夹)
                string path = Path.Combine(imagePath, imageName);   // 把路径转换为绝对路径
                image.CopyTo(new FileStream(path, FileMode.Create));
            }
            return imageName;
        }
    }
}
